const simpleDDP = require('simpleddp');
const simpleDDPLogin = require('simpleddp-plugin-login').simpleDDPLogin;
const wssUrl = 'wss://sida-meteor.liftcorecloud.com:7443/websocket';
import { openPush } from '@/apis/owner.js';
import {
	UniappDriver
} from 'simpleddp-wechat-miniprogram-dirver/UniappDriver';
import {
	throttle
} from '@/utils/tools.js'; // 节流
const app = getApp();
// 开启订阅实时数据
function IOT(option) {
	// option={
	// 	deviceIds:[],//设备id数组
	// 	connected:Function,//链接成功回调
	// 	added:Function,//添加成功回调
	// 	changed:Function,//实时上报回调
	//  isThrottle:true,//是否开启节流
	//  userId
	// }
	let server = null;
	let pushTimer = null;
	console.log('尝试开启订阅服务', option);
	const DDPconfig = {
		endpoint: wssUrl,
		SocketConstructor: UniappDriver,
		reconnectInterval: 0,
		autoConnect: true // 自动重连
	};
	if (!app.globalData.wsServer) {
		app.globalData.wsServer = new simpleDDP(DDPconfig, [simpleDDPLogin]);
		const myLoginParams = {
			user: {
				username: 'sida_property'
			},
			password: 'sidaqwe1232!!44'
		};

		app.globalData.wsServer.login(myLoginParams);
	}

	server = app.globalData.wsServer;

	this.deviceIds = option.deviceIds;
	this.updateIds = function (ids) {
		this.deviceIds = ids;
	};
	this.openPush = function () {
		console.log('定时推流');
		if (!this.deviceIds || this.deviceIds.length == 0 || !this.deviceIds[0]) {
			return;
		}
		openPush({
			deviceIds: this.deviceIds,
			userId: option.userId || 'sida-001'
		});
	};
	// 关闭socket链接
	this.close = function () {
		// server.ddpConnection.unsub(this.device);
		if (pushTimer) {// 清除定时推送
			clearTimeout(pushTimer);
			pushTimer = null;
		}
		// server.disconnect().then(() => {
		// 	console.log('关闭实时状态socket链接');
		// 	server.logout()
		// });
	};
	this.subDevices = function () {
		// 订阅 
		const deviceIds = getApp().globalData.deviceIds || [];
		// this.device = server.ddpConnection.sub('real_time_status', [...this.deviceIds]);
		for (var i = 0; i < this.deviceIds.length; i++) {
			if (deviceIds.indexOf(this.deviceIds[i]) == -1) {
				server.ddpConnection.sub('real_time_status', [this.deviceIds[i]]);
				getApp().globalData.deviceIds.push(this.deviceIds[i]);
			}
		}

		if (!pushTimer) {
			this.openPush();
			pushTimer = setTimeout(() => {
				this.openPush();
			}, 3000);
		}
	};

	// 链接成功的事件
	server.on('connected', () => {
		console.log('simpleDDP-链接成功');
		if (option.connected) {
			option.connected(res);
		}
	});
	// 文件上传的事件
	server.on('filestatus', res => {
		console.log('filestatus', res);
	});

	server.on('added', res => {
		console.log(res);
		if (option.added) {
			option.added(res);
		}
	});

	// 数据有变动事件
	server.on('changed', res => {
		if (option.isThrottle) {
			throttle(option.changed(res), 400);
		} else {
			if (option.changed) {
				option.changed(res);
			}
		}
	});
}

export {
	IOT
};
